<template>
  <el-upload
    class="avatar-uploader"
    action="http://backend-api-02.newbee.ltd/manage-api/v1/upload/file"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :headers="{ Token: token }"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon :size="40" v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import { api } from "../api/api";
import { useRoute, useRouter } from "vue-router";
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useStore } from "../store/counter";
const store = useStore();
const route = useRoute();
const imageUrl = ref("");
const emit = defineEmits(["getImage"]);
const token = ref("");
onMounted(() => {
  token.value = localStorage.getItem("token") as string;
  if (route.query.id) {
    api
      .editProductCallbackApi({ id: route.query.id as string })
      .then((res: any) => {
        imageUrl.value = res.data.goods.goodsCoverImg;

        emit("getImage", res.data);
      });
  }
});
// 图片上传成功的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = async (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  emit("getImage", response.data);
};
// 上传文件前的钩子 可以用来约束上传图片的类型或者大小
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile);
};
</script>

<style lang="scss">
.avatar-uploader {
  width: 100px;

  height: 100px;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 100px;
    height: 100px;
  }
}
</style>
